package org.ccay.ws.databind;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.ccay.enumerable.EnumItem;
import org.codehaus.jackson.map.BeanProperty;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.deser.StdDeserializerProvider;
import org.codehaus.jackson.map.type.ArrayType;
import org.codehaus.jackson.type.JavaType;

public class DeserializerProvider extends StdDeserializerProvider{
	
	/**
	 * {@link EnumItem}&lt;?>签名的正则解析表达式
	 */
	private static Pattern ENUMITEM_FILED_SIGN_REGEX = Pattern.compile("<(/?(\\w+))+;>");
	
	@SuppressWarnings("unchecked")
    protected JsonDeserializer<Object> _createDeserializer(DeserializationConfig config, 
            JavaType type, BeanProperty property)
        throws JsonMappingException
    {
		//可枚举类型解析器
		if(EnumItem.class.isAssignableFrom((Class<?>) type.getRawClass())){
			//使用java语言中的枚举类型
			if(type.getRawClass().isEnum()){
				return (JsonDeserializer<Object>) new EnumItemDeserializer(type.getRawClass(),type.getRawClass().getSimpleName());
			}
			//使用EnumItem<? extends EnumItem >泛型申明的对象
			if(type.getRawClass().isInterface()){
				String enumType = null;
				Matcher regexMatcher = ENUMITEM_FILED_SIGN_REGEX.matcher(type.getGenericSignature());
				if (regexMatcher.find()) {
					enumType = regexMatcher.group(2);
				}
				if(enumType != null){
					return (JsonDeserializer<Object>) new EnumItemDeserializer(type.getRawClass(),enumType);
				}
			}
		}
		//可枚举类型集合解析器
		if(type.isContainerType()){
			if (type.isArrayType()) {
                return (JsonDeserializer<Object>)_factory.createArrayDeserializer(config, this,
                        (ArrayType) type, property);
            }
		}
		
		//如果是PlainEnumItem 或其他情况 则使用默认解析器
		return super._createDeserializer(config, type, property);
    }

}
